# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, fields, models, _, tools
import json
import datetime


class FapiaoOutInvoice(models.Model):
    _inherit = 'fp.fapiao'

    expense_id = fields.Many2one('fp.expense', string="Expense", copy=False,)


class FpExpense(models.Model):

    _name = "fp.expense"
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = "Fapiao Expense"
    _order = "date desc, id desc"

    name = fields.Char(
        string='Order Number', required=True, copy=False, readonly=True,
        states={'draft': [('readonly', False)]}, index=True,
        default=lambda self: _('New'))

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company)

    user_id = fields.Many2one(
        'res.users', string='User', index=True, default=lambda self: self.env.user)

    state = fields.Selection([
        ('draft', 'Draft'),
        ('confirmed', 'Confirmed'),
        ('done', 'Locked'),
        ('cancel', 'Cancelled'),
    ], string='Status', readonly=True, copy=False, index=True, default='draft')

    date = fields.Date(
        string="Expense Date",
        states={'done': [('readonly', True)]},
        default=fields.Date.context_today)

    partner_id = fields.Many2one(
        'res.partner', string='Empolyee', readonly=True,
        states={'draft': [('readonly', False)]},
        required=True, index=True)

    fapiao_ids = fields.One2many(
        'fp.fapiao', 'expense_id', string="Fapiaos", readonly=True, copy=False,)

    attachment_number = fields.Integer(
        'Number of Attachments', compute='_compute_attachment_number')

    note = fields.Text()

    def _compute_attachment_number(self):
        attachment_data = self.env['ir.attachment']._read_group(
            [('res_model', '=', 'fp.expense'), ('res_id', 'in', self.ids)], ['res_id'], ['res_id'])
        attachment = dict((data['res_id'], data['res_id_count'])
                          for data in attachment_data)
        for expense in self:
            expense.attachment_number = attachment.get(expense._origin.id, 0)

    def _update_name(self):
        for one in self:
            if not one.name or one.name == _('New'):
                now = datetime.datetime.now()
                now1 = now.strftime('%Y%m%d')
                one.name = now1 + str(one.id).rjust(12, '0')

    @api.model_create_multi
    def create(self, vals_list):
        records = super().create(vals_list)
        records._update_name()
        return records

    def action_confirm(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'draft')])
        for one in self2:
            one.write({'state': 'confirmed'})

    def action_cancel(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])

        for one in self2:
            one.write({'state': 'cancel'})

    def action_draft(self):
        self2 = self.search([('id', 'in', self.ids), ('state', '=', 'cancel')])
        for one in self2:
            one.write({'state': 'draft'})

    def action_done(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])
        for one in self2:
            one.write({'state': 'done'})

    def action_create_fapiap(self):
        self2 = self.search([('id', 'in', self.ids),
                             ('state', 'in', ['draft', 'confirmed'])])
        self3 = self2.filtered(lambda r: r.attachment_number > 0)

        values_list = []
        for one in self3:
            attachments = self.env['ir.attachment'].search(
                [('res_model', '=', 'fp.expense'), ('res_id', 'in', one.ids)])

            for attach in attachments:
                vals = {
                    # 'time_fapiao': one.time_fapiao,
                    'company_id': one.company_id.id,
                    'user_id': one.user_id.id,
                    'type': 'in_invoice',
                    'expense_id':  one.id,
                    'attachment_id': attach.id
                }

                values_list.append(vals)

        fapiao = self.env['fp.fapiao']
        if values_list:
            fapiao = fapiao.create(values_list)

        return fapiao
